package com.liushao.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.liushao.dto.ExcelDictDTO;
import com.liushao.mapper.DictMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: untitled1
 * @ClassName ExcelDictDTOListener
 * @description:  监听类
 * @author: 陈修华
 * @create: 2025−01-07 15:27
 * @Version 1.0
 **/

public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {
    private static  final  int BATCH_COUNT=5;//每次5条

    List<ExcelDictDTO> list = new ArrayList<>();//集合存储
    //@Autowired
    private DictMapper dictMapper;

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext context) {
        //每遍历一行数据都执行这里
        list.add(data);//

        if(list.size()>=BATCH_COUNT){
             //进行数据保存
            saveData();
            //清楚 12345
            list.clear();
        }

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //进行数据保存
        saveData();
    }

    private  void saveData(){
        //批量添加
          dictMapper.insertBach(list);
        System.out.println("--------存入数据--------");
    }
}
